<script setup lang="ts">
import { inject, onMounted, ref } from 'vue'
const http: any = inject('http');
const loading = ref(true);

interface IOilPriceModal {
  area: string;
  oilPrice92: string;
  oilPrice95: string;
  oilPrice98: string;
  oilPrice0: string;
  updateTime: string;
};

interface IRecentOilDate {
  id: string;
  date: string;
  week: number
}

interface IResultModal {
  code: number;
  data: IOilPriceModal[];
  msg: string;
}

interface IResultRecentOilDateModal {
  code: number;
  data: IRecentOilDate[];
  msg: string;
}

const moveItemToFront = (array: IOilPriceModal[], value: string) => {
  // 查找目标值的索引
  const index = array.findIndex(item => item.area === value);

  // 如果找到了目标值
  if (index > -1) {
    // 使用解构赋值将找到的元素移到数组开头
    [array[0], array[index]] = [array[index], array[0]];
  }

  return array;
}

const data = ref<IOilPriceModal[] | null>(null);
const recentOilData = ref<IRecentOilDate | null>(null);

const getOilList = () => {
  http.get('/api/oil/get').then((res: IResultModal) => {
    if (res.code === 1) {
      data.value = moveItemToFront(res.data, window.localStorage.getItem('province') as string);
      loading.value = false;
    }
  })
}

const getRecentOil = () => {
  http.get('/api/oil/geRecentDate').then((res: IResultRecentOilDateModal) => {
    if (res.code === 1) {
      console.log(res);
      recentOilData.value = res.data[0];
    }
  })
}

onMounted(() => {
  getOilList();
  getRecentOil();
})

const tableRowClassName = ({
  row,
  rowIndex,
}: {
  row: any
  rowIndex: number
}) => {
  if (rowIndex === 0) {
    return 'warning-row'
  }
  return ''
}
</script>

<template>
  <div class="oilPrice" v-loading="loading">
    <h1>今日国内油价查询(油价最近更新时间{{ recentOilData?.date.split('T')[0] }})</h1>
    <span></span>
    <el-table :data="data" border style="width: 100%;" size="large" :row-class-name="tableRowClassName"
      highlight-current-row>
      <el-table-column prop="area" label="地区" />
      <el-table-column prop="oilPrice92" label="92#" />
      <el-table-column prop="oilPrice95" label="95#" />
      <el-table-column prop="oilPrice98" label="98#" />
      <el-table-column prop="oilPrice0" label="0#" />
      <el-table-column prop="updateTime" label="更新时间" />
    </el-table>
  </div>
</template>

<style scoped>
.oilPrice h1 {
  display: flex;
  justify-content: center;
  padding-bottom: 20px;
}

::v-deep .warning-row {
  /* border: 5px solid brown !important; */
  background-color: #c6e2ff;
  color: #fff;
}

::v-deep .el-table tbody tr:hover td {
  background-color: #c6e2ff !important;
  color: #fff;
  cursor: default;
  /* 可选，改变鼠标指针形状 */
}
</style>